package com.webssh.service.handler;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 *  
 * @author zhanshuw
 *     	   2018年6月21日
 * 
 */
public class WSHandler extends AbstractWebSocketHandler{
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	protected static ConcurrentHashMap<WebSocketSession, HandlerProcess> map = new ConcurrentHashMap<>();
	
	@Override
	public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception {
		logger.debug("ws:{}已关闭", arg0.getId());
		close(arg0);
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession ws) throws Exception {
		HandlerProcess h = HandlerFactory.getHandler(ws);
		map.put(ws, h);
		h.init();
	}

	@Override
	protected void handleTextMessage(WebSocketSession ws, TextMessage message) throws Exception {
		String obj = message.getPayload();
		logger.debug("recived msg:{}", obj);
		if("exit".equals(obj)){
			close(ws);
		}else{
			if(map.get(ws) != null){
				map.get(ws).handleMessage(obj.toString());
			}
		}
	}

	@Override
	public void handleTransportError(WebSocketSession ws, Throwable arg1) throws Exception {
		close(ws);
	}

	private void close(WebSocketSession arg0) throws IOException{
		HandlerProcess h = map.remove(arg0);
		if(h != null){
			h.close();
		}
		if(arg0 !=null && arg0.isOpen()){
			try {
				logger.info("主动关闭ws:{}", arg0.getId());
				arg0.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/** 
	 * 由httpSession id 查找webSocketSession
	 * @param sessionId
	 * @return
	 */
	public static WebSocketSession getWebSocketSession(String sessionId){
		if(sessionId == null)return null;
		Set<WebSocketSession> set = map.keySet();
		for(WebSocketSession ws: set){
			if(sessionId.equals(ws.getAttributes().get(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME))){
				return ws;
			}
		}
		return null;
	}
}
